﻿using System;
using System.Threading.Tasks;

using Agile;
using Agile.Service.Rbac;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

using Web.Factories;

namespace Web.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    [AllowAnonymous]
    public class LoginController : Controller
    {
        private readonly VerifyCode _verifyCode;
        private readonly IUserService _userService;
        private readonly ISettingModelFactory _settingModelFactory;
        private readonly IAuth _auth;
        public LoginController(IAuth auth,VerifyCode verifyCode, IUserService userService, ISettingModelFactory settingModelFactory)
        {
            _auth = auth;
            _verifyCode = verifyCode;
            _userService = userService;
            _settingModelFactory = settingModelFactory;
        }
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Index(string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return View("Error", new string[] { "您已经登录！" });
            }
            ViewBag.returnUrl = returnUrl;
            var model = _settingModelFactory.PrepareGeneralCommonSettingsModel();
            return View(model);
        }
        [HttpGet]
        public ActionResult GetAuthCode()
        {
            return File(_verifyCode.GetVerifyCode(), @"image/Gif");
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> CheckLogin(string username, string password, string code)
        {
            try
            {
                var verifycode = HttpContextCore.Current.Session.Get<string>("agile_session_verifycode");
                if (verifycode == null || code.ToLower() != verifycode)
                {
                    return Content(new Result { Success = false, StatusCode = 500, Message = "验证码错误，请重新输入" }.ToJson());
                }
                var result = await _auth.LoginAsync( username, password);
                return Content(result.ToJson());
            }
            catch (Exception ex)
            {
                return Content(new Result { Success = false, StatusCode = 500, Message = "登录失败，" + ex.Message }.ToJson());
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> OutLogin()
        {
            await _auth.LogoutAsync();
            return Redirect("/Login");
        }
    }
}